import React, { useEffect } from 'react';
import { Form, Input, Checkbox, Button, message } from 'antd';
import type { FormProps } from 'antd';
import { useNavigate } from 'react-router-dom';

import { IUserLogin, userLoginService } from '../../api/common';

const Login = () => {
  const navigate = useNavigate();

  const [form] = Form.useForm();

  const handleUpdateValues: FormProps<IUserLogin>['onValuesChange'] = (values) => {
    const { username, password, remember } = values;
    if (remember) {
      const userInfo = { username, password };
      localStorage.setItem('user', JSON.stringify(userInfo));
    } else {
      localStorage.removeItem('user');
    }
  };
  const onFinish: FormProps<IUserLogin>['onFinish'] = async (values) => {
    const { username, password } = values;

    const { data } = await userLoginService({ username, password });
    if (data && data.length > 0) {
      message.success('登录成功');
    } else {
      message.error('该账户不存在，请重新登录');
    }
  };

  useEffect(() => {
    const userInfo = localStorage.getItem('user');
    if (userInfo) {
      const { username, password } = JSON.parse(userInfo);
      form.setFieldsValue({ username, password });
    }
  }, []);

  return (
    <div className="w-full h-full flex justify-center items-center bg-blue-300">
      <div className="w-2/6 h-3/6 bg-white rounded-lg flex flex-col">
        <h3 className="py-5 text-center border-b-red-400">登录</h3>
        <div className="flex-1 px-10 py-10">
          <Form
            form={form}
            initialValues={{ remember: true }}
            onValuesChange={handleUpdateValues}
            onFinish={onFinish}
            autoComplete="off"
            labelAlign="left"
            labelCol={{ span: 6 }}
          >
            <Form.Item<IUserLogin>
              label="用户名"
              name="username"
              rules={[
                {
                  validator: (_, value) => {
                    if (!/^\S+@\S+\.\S+$/.test(value) && !/^[\+]?[\d]{9,15}$/.test(value)) {
                      return Promise.reject(new Error('请输入有效的手机号或邮箱'));
                    }
                    return Promise.resolve();
                  }
                }
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item<IUserLogin>
              label="密码"
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item<IUserLogin>
              name="remember"
              valuePropName="checked"
              wrapperCol={{ offset: 8, span: 16 }}
            >
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <Form.Item className="text-center">
              <Button className="w-[120px] h-[35px]" type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div
          className="px-10 py-10 text-right text-cyan-400 cursor-pointer"
          onClick={() => navigate('/register')}
        >
          没有账号，请去注册
        </div>
      </div>
    </div>
  );
};

export default Login;
